package com.qdxwx.web.config;

import freemarker.template.DefaultObjectWrapper;
import freemarker.template.SimpleDate;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;


import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * @author ZhiYong
 * @createTime 2021/6/29
 * @description
 */
@Configuration
public class FreemarkerConfigurer {
    @Autowired
    private freemarker.template.Configuration configuration;

    @PostConstruct
    public void setConfigure() throws Exception {
        configuration.setSharedVariable("staticSite", "");
        configuration.setObjectWrapper(new DefaultObjectWrapper(freemarker.template.Configuration.VERSION_2_3_31) {
            @Override
            public TemplateModel wrap(Object object) throws TemplateModelException {
                if (object instanceof LocalDate) {
                    return new SimpleDate(Date.valueOf((LocalDate) object));
                }
                if (object instanceof LocalTime) {
                    return new SimpleDate(Time.valueOf((LocalTime) object));
                }
                if (object instanceof LocalDateTime) {
                    return new SimpleDate(Timestamp.valueOf((LocalDateTime) object));
                }
                return super.wrap(object);
            }
        });
    }
}
